package cn.kgm.makeGodV2.ruleEngine;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Version 1.8
 * @Author: Kappi
 * @Date: 2025-9-25 11:18
 * @Description: cn.kgm.makeGodV2.ruleEngine.ConditionExecutor
 */
/**
 * 增强的条件执行器 - 支持通过规则引擎执行单个条件
 */
public class ConditionExecutor {

    /**
     * 执行单个条件配置（支持通过规则引擎执行）
     */
    public static RuleResult<Boolean> executeCondition(ConditionConfig condition, RuleContext parentContext) {
        if (condition == null) {
            return RuleResult.fail("条件配置为空");
        }

        String conditionType = condition.getType();

        // 如果是逻辑操作符，使用规则引擎执行（但避免递归）
        if (isLogicalOperator(conditionType)) {
            return executeLogicalConditionViaEngine(condition, parentContext);
        } else {
            // 原子条件直接执行
            return executeAtomicCondition(condition, parentContext);
        }
    }

    private static boolean isLogicalOperator(String conditionType) {
        return "AND".equals(conditionType) || "OR".equals(conditionType) || "NOT".equals(conditionType);
    }

    private static RuleResult<Boolean> executeLogicalConditionViaEngine(ConditionConfig condition, RuleContext parentContext) {
        try {
            SimpleRuleEngine engine = SimpleRuleEngine.getInstance();

            // 创建新的上下文，包含条件配置
            RuleContext context = new RuleContext();
            context.getParams().putAll(parentContext.getParams()); // 复制父上下文参数
            context.setParam("conditionConfig", condition);

            return engine.executeRule(condition.getType(), context);
        } catch (Exception e) {
            return RuleResult.fail("逻辑条件执行失败: " + e.getMessage());
        }
    }

    private static RuleResult<Boolean> executeAtomicCondition(ConditionConfig condition, RuleContext context) {
        String conditionType = condition.getType();
        switch (conditionType) {
            case "REALM_CHECK":
                return executeRealmCheck(condition, context);
            case "SINGLE_ITEM_CHECK":
                return executeSingleItemCheck(condition, context);
            case "RANDOM_TRIGGER":
                return executeRandomTrigger(condition, context);
            default:
                return RuleResult.fail("未知的条件类型: " + conditionType);
        }
    }

    // 以下原子条件的执行方法与之前相同
    private static RuleResult<Boolean> executeRealmCheck(ConditionConfig condition, RuleContext context) {
        String requiredRealm = (String) condition.getValue();
        String playerRealm = context.getParam("playerRealm", String.class);

        Map<String, Integer> realmLevels = new HashMap<>();
        realmLevels.put("练气期", 1);
        realmLevels.put("筑基期", 2);
        realmLevels.put("金丹期", 3);
        realmLevels.put("元婴期", 4);
        realmLevels.put("化神期", 5);
        realmLevels.put("大乘期", 6);
        int playerLevel = realmLevels.getOrDefault(playerRealm, 0);
        int requiredLevel = realmLevels.getOrDefault(requiredRealm, 0);

        boolean canAccess = playerLevel >= requiredLevel;
        String message = canAccess ?
                "境界要求满足" : "境界不足，需要" + requiredRealm + "以上";

        return RuleResult.success(message, canAccess);
    }

    @SuppressWarnings("unchecked")
    private static RuleResult<Boolean> executeSingleItemCheck(ConditionConfig condition, RuleContext context) {
        Map<String, Integer> requiredItem = (Map<String, Integer>) condition.getValue();
        Map<String, Integer> playerItems = context.getParam("playerItems", Map.class);

        if (playerItems == null) playerItems = new HashMap<>();

        for (Map.Entry<String, Integer> entry : requiredItem.entrySet()) {
            String itemId = entry.getKey();
            int requiredCount = entry.getValue();
            int playerCount = playerItems.getOrDefault(itemId, 0);

            if (playerCount >= requiredCount) {
                String message = String.format("拥有%s %d个(需要%d个)", itemId, playerCount, requiredCount);
                return RuleResult.success(message, true);
            }
        }

        Map.Entry<String, Integer> entry = requiredItem.entrySet().iterator().next();
        String message = String.format("缺少%s，需要%d个", entry.getKey(), entry.getValue());
        return RuleResult.success(message, false);
    }

    private static RuleResult<Boolean> executeRandomTrigger(ConditionConfig condition, RuleContext context) {
        double triggerRate = (Double) condition.getValue();
        double randomValue = Math.random();
        boolean triggered = randomValue <= triggerRate;

        String message = triggered ?
                String.format("随机事件触发成功 (%.1f%%几率)", triggerRate * 100) :
                String.format("随机事件未触发 (%.1f%%几率)", triggerRate * 100);

        return RuleResult.success(message, triggered);
    }

    // 保留原有的逻辑条件执行方法，供规则引擎调用
    static RuleResult<Boolean> executeAndCondition(ConditionConfig condition, RuleContext context) {
        List<ConditionConfig> subConditions = condition.getConditions();
        if (subConditions == null || subConditions.isEmpty()) {
            return RuleResult.fail("AND条件缺少子条件");
        }

        boolean allSuccess = true;
        List<String> messages = new ArrayList<>();

        for (ConditionConfig subCondition : subConditions) {
            RuleResult<Boolean> subResult = executeCondition(subCondition, context);
            if (!subResult.isSuccess() || !subResult.getData()) {
                allSuccess = false;
                messages.add(subResult.getMessage());
            }
        }

        String message = allSuccess ? "所有条件都满足" : "条件不满足: " + String.join("; ", messages);
        return RuleResult.success(message, allSuccess);
    }

    static RuleResult<Boolean> executeOrCondition(ConditionConfig condition, RuleContext context) {
        List<ConditionConfig> subConditions = condition.getConditions();
        if (subConditions == null || subConditions.isEmpty()) {
            return RuleResult.fail("OR条件缺少子条件");
        }

        boolean anySuccess = false;
        List<String> successMessages = new ArrayList<>();
        List<String> failMessages = new ArrayList<>();

        for (ConditionConfig subCondition : subConditions) {
            RuleResult<Boolean> subResult = executeCondition(subCondition, context);
            if (subResult.isSuccess() && subResult.getData()) {
                anySuccess = true;
                successMessages.add(subResult.getMessage());
            } else {
                failMessages.add(subResult.getMessage());
            }
        }

        String message = anySuccess ?
                "满足以下条件之一: " + String.join("; ", successMessages) :
                "所有条件都不满足: " + String.join("; ", failMessages);

        return RuleResult.success(message, anySuccess);
    }

    static RuleResult<Boolean> executeNotCondition(ConditionConfig condition, RuleContext context) {
        List<ConditionConfig> subConditions = condition.getConditions();
        if (subConditions == null || subConditions.size() != 1) {
            return RuleResult.fail("NOT条件必须有且只有一个子条件");
        }

        RuleResult<Boolean> subResult = executeCondition(subConditions.get(0), context);
        boolean notResult = !(subResult.isSuccess() && subResult.getData());
        String message = notResult ? "条件取反成功" : "条件取反失败";

        return RuleResult.success(message, notResult);
    }
}
